if SERVER then
	local meta = FindMetaTable("Player")
	
	function meta:KOwner()
		return self:IsUserGroup("owner")
	end
	
	function meta:KAdmin()
		return self:IsUserGroup("admin") || self:IsUserGroup("owner")
	end
	
	function meta:KModerator()
		return self:IsUserGroup("moderator")
	end
	
	function meta:SetRank(arg)
		self:SetUserGroup(tostring(arg))
		
		if SQL_ACTIVE then
			local query = "SELECT * FROM kontrol_ranks WHERE id='" .. self:SteamID() .. "'"
			tmysql.query(query, function(result, status, error)
				if #result > 0 then
					query = "UPDATE kontrol_ranks SET rank='" .. tostring(arg) .. "' WHERE id='" .. self:SteamID() .. "'"
					tmysql.query(query)
				else
					query = "INSERT INTO kontrol_ranks (`id`, `rank`) VALUES ('" .. self:SteamID() .. "', '" .. tostring(arg) .. "')"
					tmysql.query(query)
				end
			end, 1)
		else
			local query = "SELECT * FROM kontrol_ranks WHERE id='" .. self:SteamID() .. "'"
			local result = sql.Query(query)
			if result then
				query = "UPDATE kontrol_ranks SET rank='" .. tostring(arg) .. "' WHERE id='" .. self:SteamID() .. "'"
				result = sql.Query(query)
			else
				query = "INSERT INTO kontrol_ranks (`id`, `rank`) VALUES ('" .. self:SteamID() .. "', '" .. tostring(arg) .. "')"
				result = sql.Query(query)
			end
		end
	end
	
	hook.Add("PlayerAuthed", "kontrol_SetRanksOnJoin", function(pl, steamid, uid)
		if SQL_ACTIVE then
			local query = "SELECT * FROM kontrol_ranks WHERE id='" .. steamid .. "'"
			tmysql.query(query, function(result, status, error)
				if #result > 0 then
					pl:SetUserGroup(result[1]["rank"])
				end
			end, 1)
		else
			local query = "SELECT * FROM kontrol_ranks WHERE id='" .. steamid .. "'"
			local result = sql.Query(query)
			if result then
				pl:SetUserGroup(result[1]["rank"])
			end
		end
	end)
	
	hook.Add("InitPostEntity", "kontrol_RankInit", function()
		if SQL_ACTIVE then
			//Create Rank table if not already exists
			local query = "CREATE TABLE IF NOT EXISTS kontrol_ranks (id VARCHAR(255), rank TEXT)"
			tmysql.query(query)
		else
			if !sql.TableExists("kontrol_ranks") then
				local query = "CREATE TABLE kontrol_ranks (id VARCHAR(255), rank TEXT)"
				local result = sql.Query(query)
			end
		end
	end)
end